# from urllib.parse import quote
import datetime
import json
import random

from lxml import html
import cssutils
import requests

from src import utils
from src.verification_captcha import VerificationCaptcha


def get_css_properties(sheet):
    # 创建一个字典来保存属性
    display_list = []
    # 遍历所有的规则
    for rule in sheet:
        if rule.type == rule.STYLE_RULE:
            for property in rule.style:
                if property.name == 'display' and property.value == 'block':
                    display_list.append(rule.selectorText)

    return display_list


def get_form_index(tree, displayList):
    for i in range(5):
        VisaType = tree.xpath('//input[@id="VisaType' + str(i + 1) + '"]/..')[0].get('class')
        for tt in VisaType.split(' '):
            if '.' + tt in displayList:
                return str(i + 1)


headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,'
              '*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'Accept-language': 'zh,en-GB;q=0.9,en;q=0.8,zh-CN;q=0.7',
    'Accept-Encoding': 'gzip, deflate, br, zstd',
    'Cache-Control': 'no-cache',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/122.0.0.0 Safari/537.36',
    'Referer': 'https://spain.blscn.cn/CHN/Bls/VisaTypeVerification',
    'Pragma': 'no-cache',
    'Sec-Ch-Ua': 'Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
    'Sec-Ch-Ua-Mobile': '?0',
    'Sec-Ch-Ua-Platform': 'Windows',
    'Sec-Fetch-Dest': 'document',
    'upgrade-insecure-requests': '1'
}


class VisaVerification:
    def __init__(self, cookies, visaType, visaSubType, appointmentCategoryId, location):
        self.cookies = cookies
        self.visaType = visaType
        self.visaSubType = visaSubType
        self.appointmentCategoryId = appointmentCategoryId
        self.location = location

    def get_request_token(self):
        url = 'https://spain.blscn.cn/CHN/bls/visatypeverification'
        htmlResponse = requests.get(url, headers=utils.get_headers(), cookies=self.cookies)
        if htmlResponse.status_code == 200:
            tree = html.fromstring(htmlResponse.content)
            verificationToken = tree.xpath('//input[@name="__RequestVerificationToken"]')[0].get('value')

            return verificationToken
        return ''

    def get_captcha_data(self):
        verifi = VerificationCaptcha('/CHN/NewCaptcha/GenerateCaptcha', cookies=self.cookies, is_login=False)
        captcha_data = verifi.get_captcha_data()
        return captcha_data

    def get_appoint_html(self):
        token = self.get_request_token()
        captcha_data = self.get_captcha_data()
        if captcha_data is None:
            # 没有通过验证需要重新获取验证
            return ''
        data = {
            'CaptchaData': captcha_data,
            '__RequestVerificationToken': token,
            'X-Requested-With': 'XMLHttpRequest'
        }
        url = 'https://spain.blscn.cn/CHN/bls/VisaTypeVerification'
        res = requests.post(url, headers=utils.get_headers(), cookies=self.cookies, data=data)
        if res.status_code == 200:
            result_json = res.json()
            if result_json['success']:
                res = requests.get('https://spain.blscn.cn' + res.json()['returnUrl'], headers=headers,
                                   cookies=self.cookies)

                tree = html.fromstring(res.content)

                style_tags = tree.xpath('//style')
                stylesheet = cssutils.parseString(style_tags[1].text)
                displayList = get_css_properties(stylesheet)
                index = get_form_index(tree, displayList)

                form_data = utils.get_form_data(tree)

                form_data['VisaType' + index] = self.visaType
                form_data['AppointmentCategoryId' + index] = self.appointmentCategoryId
                form_data['VisaSubType' + index] = self.visaSubType
                form_data['Location' + index] = self.location
                form_data['X-Requested-With'] = 'XMLHttpRequest'

                form_data['AppointmentFor1'] = form_data['AppointmentFor2'] = form_data['AppointmentFor3'] = form_data['AppointmentFor4'] = form_data['AppointmentFor5'] = 'Individual'

                rsp_data = []
                now = datetime.datetime.now()
                start = now - datetime.timedelta(seconds=10)
                for key in ['VisaType', 'VisaSubType', 'Location', 'AppointmentCategoryId']:
                    total = random.randint(800, 1400)
                    rsp_data.append({
                        'Id': key + index,
                        'Selected': True,
                        'Start': start,
                        'End': start + datetime.timedelta(seconds=total / 1000),
                        'Total': total
                    })
                    start = start + datetime.timedelta(seconds=total / 500)

                form_data['ResponseData'] = json.dumps(rsp_data, default=utils.datetime_handler)

                url = 'https://spain.blscn.cn/CHN/bls/VisaType'
                print(form_data)
                res = requests.post(url, headers=headers, cookies=self.cookies, data=form_data)
                if res.status_code == 200:
                    result_json = res.json()
                    print(result_json)
                    if result_json['success']:
                        res = requests.get('https://spain.blscn.cn' + res.json()['returnUrl'], headers=headers,
                                           cookies=self.cookies)
                        if res.status_code == 200:
                            return res.content

        return ''
